package com.thyme.util;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class EntityGenerator {
    private final static Logger LOGGER = LoggerFactory.getLogger(EntityGenerator.class);

    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://161.189.76.107:3307/wyt?useSSL=false&useUnicode=true&characterEncoding=UTF-8";
    private static final String USERNAME = "wyt";
    private static final String PASSWORD = "WYT#2020";

    private static final String SQL = "SELECT * FROM ";// 数据库操作

    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            LOGGER.error("can not load jdbc driver", e);
        }
    }

    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            LOGGER.error("get connection failure", e);
        }
        return conn;
    }

    /**
     * 关闭数据库连接
     *
     * @param conn
     */
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                LOGGER.error("close connection failure", e);
            }
        }
    }

    /**
     * 获取数据库下的所有表名
     */
    public static List<String> getTableNames() {
        List<String> tableNames = new ArrayList<>();
        Connection conn = getConnection();
        ResultSet rs = null;
        try {
            //获取数据库的元数据
            DatabaseMetaData db = conn.getMetaData();
            //从元数据中获取到所有的表名
            rs = db.getTables(null, null, null, new String[]{"TABLE"});
            while (rs.next()) {
                tableNames.add(rs.getString(3));
            }
        } catch (SQLException e) {
            LOGGER.error("getTableNames failure", e);
        } finally {
            try {
                rs.close();
                closeConnection(conn);
            } catch (SQLException e) {
                LOGGER.error("close ResultSet failure", e);
            }
        }
        return tableNames;
    }

    /**
     * 获取表中所有字段名称
     *
     * @param tableName 表名
     * @return
     */
    public static List<String> getColumnNames(String tableName) {
        List<String> columnNames = new ArrayList<>();
        //与数据库的连接
        Connection conn = getConnection();
        PreparedStatement pStemt = null;
        String tableSql = SQL + tableName;
        try {
            pStemt = conn.prepareStatement(tableSql);
            //结果集元数据
            ResultSetMetaData rsmd = pStemt.getMetaData();
            //表列数
            int size = rsmd.getColumnCount();
            for (int i = 0; i < size; i++) {
                columnNames.add(rsmd.getColumnName(i + 1));
            }
        } catch (SQLException e) {
            LOGGER.error("getColumnNames failure", e);
        } finally {
            if (pStemt != null) {
                try {
                    pStemt.close();
                    closeConnection(conn);
                } catch (SQLException e) {
                    LOGGER.error("getColumnNames close pstem and connection failure", e);
                }
            }
        }
        return columnNames;
    }

    /**
     * 获取表中所有字段类型
     *
     * @param tableName
     * @return
     */
    public static List<String> getColumnTypes(String tableName) {
        List<String> columnTypes = new ArrayList<>();
        //与数据库的连接
        Connection conn = getConnection();
        PreparedStatement pStemt = null;
        String tableSql = SQL + tableName;
        try {
            pStemt = conn.prepareStatement(tableSql);
            //结果集元数据
            ResultSetMetaData rsmd = pStemt.getMetaData();
            //表列数
            int size = rsmd.getColumnCount();
            for (int i = 0; i < size; i++) {
                columnTypes.add(rsmd.getColumnTypeName(i + 1));
            }
        } catch (SQLException e) {
            LOGGER.error("getColumnTypes failure", e);
        } finally {
            if (pStemt != null) {
                try {
                    pStemt.close();
                    closeConnection(conn);
                } catch (SQLException e) {
                    LOGGER.error("getColumnTypes close pstem and connection failure", e);
                }
            }
        }
        return columnTypes;
    }

    /**
     * 获取表中字段的所有注释
     *
     * @param tableName
     * @return
     */
    public static List<String> getColumnComments(String tableName) {
        List<String> columnTypes = new ArrayList<>();
        //与数据库的连接
        Connection conn = getConnection();
        PreparedStatement pStemt = null;
        String tableSql = SQL + tableName;
        List<String> columnComments = new ArrayList<>();//列名注释集合
        ResultSet rs = null;
        try {
            pStemt = conn.prepareStatement(tableSql);
            rs = pStemt.executeQuery("show full columns from " + tableName);
            while (rs.next()) {
                columnComments.add(rs.getString("Comment"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                    closeConnection(conn);
                } catch (SQLException e) {
                    LOGGER.error("getColumnComments close ResultSet and connection failure", e);
                }
            }
        }
        return columnComments;
    }

    public static List<TableInfos> getTableInfo(String tableName) {
        List<TableInfos> columnTypes = new ArrayList<>();
        //与数据库的连接
        Connection conn = getConnection();
        PreparedStatement pStemt = null;
        String tableSql = SQL + tableName;
        ResultSet rs = null;
        try {
            pStemt = conn.prepareStatement(tableSql);
            rs = pStemt.executeQuery("show full columns from " + tableName);
            while (rs.next()) {
                TableInfos table = new TableInfos();
                table.setColumnComments(rs.getString("Comment"));
                table.setColumnNames(rs.getString("Field"));
                table.setColumnTypes(rs.getString("Type"));
                columnTypes.add(table);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                    closeConnection(conn);
                } catch (SQLException e) {
                    LOGGER.error("getColumnComments close ResultSet and connection failure", e);
                }
            }
        }
        return columnTypes;
    }

    public static void test() {
        List<String> tableNames = getTableNames();
        System.out.println("tableNames:" + tableNames);
        for (String tableName : tableNames) {
            System.out.println("ColumnNames:" + getColumnNames(tableName));
            System.out.println("ColumnTypes:" + getColumnTypes(tableName));
            System.out.println("ColumnComments:" + getColumnComments(tableName));
        }
    }

    public static void main(String[] args) {
        String tableName = "wyt_waybill";
        List<TableInfos> list = getTableInfo(tableName);
        System.out.println(JSONObject.toJSONString(list));
        LOGGER.info(JSONObject.toJSONString(list));
        //File file = new File("D:\\codeInit\\" + tableName + ".java");
        StringBuilder sb = new StringBuilder();
        //类开头
        sb.append("public class ");
        sb.append(Character.toUpperCase(tableName.charAt(0)));
        sb.append(toNewString(tableName.substring(1)));
        sb.append("{");
        sb.append("\n");

        /*  **/
        //遍历属性
        for (TableInfos column : list) {
            if (StringUtils.isNotBlank(column.getColumnComments())) {
                // 增加备注
                sb.append("@ApiModelProperty(value = \"${value}\")".replace("${value}", column.getColumnComments()));
                sb.append("\n");
            }
            sb.append("private ");

            if (column.getColumnTypes().contains("int")) {
                sb.append("Integer ");
            } else if (column.getColumnTypes().contains("timestamp")) {
                sb.append("Date ");
            } else if (column.getColumnTypes().contains("decimal")) {
                sb.append("Double ");
            } else {
                sb.append("String ");
            }
            sb.append(toNewString(column.getColumnNames()));
            sb.append(";\n");
            sb.append("\n");
        }
        // 类结尾
        sb.append("}");
        System.out.println(sb.toString());
    }

    public static String toNewString(String key) {
        StringBuilder sbr = new StringBuilder();
        char[] chars = key.toCharArray();
        boolean toUpFlag = false;
        for (char c : chars) {
            if (c == '_') {
                toUpFlag = true;
                continue;
            } else {
                if (toUpFlag) {
                    sbr.append(Character.toUpperCase(c));
                    toUpFlag = false;
                } else {
                    sbr.append(c);
                }
            }
        }
        return sbr.toString();
    }
}


@Data
class TableInfos {
    private String columnNames;
    private String columnTypes;
    private String columnComments;
}
